%==========================================================================
%=  This file is part of the Sound Restoration Project
%=  (c) Copyright Industrial Mathematics Institute
%=                University of South Carolina, Department of Mathematics
%=  ALL RIGHTS RESERVED
%=
%=  Author: Borislav Karaivanov
%==========================================================================

%==========================================================================
% List of the files on which this procedure depends:
%
% readdpx.m
% Image processing toolbox
%
%==========================================================================

%==========================================================================
% The function "readImageFile" reads in a given image file which can be in
% either dpx or any other image format readable by the built-in Matlab
% functionality.
% INPUT: "fileName" is string specifying the name of the image file to be
% read.
% "fileExt" is an optional string specifying the file extension. This would
% be redundant information as the file extension can be extracted from the
% file name. However, it allows to save resources by not extracting the
% extension for each file in series but doing it only for the first of
% them.
% OUTPUT: "imageArr" returns a 2D image array holding the pixel values read
% from the given image file.
% "bitDepth" returns the number of bits used to encode each pixel value.
%==========================================================================
function [imageArr, bitDepth] = readImageFile(fileName, fileExt)

if (nargin < 2)
    % Extract the file extension.
    dotIndArr = regexp(fileName, '\.');
    fileExt = fileName((dotIndArr(end) + 1):end);
end

% Use the appropriate file reader depending on whether the given file is in
% dpx or in a different image format readable by the built-in Matlab
% functionality.
if (strcmpi(fileExt, 'dpx') == true)
    % Read in the given dpx file.
    [imageArr, details] = readdpx(fileName);
    bitDepth = double(details.ImageDetails.ImageElementDetailsParsed(1).BitSize);
elseif (isempty(imformats(fileExt)) == false)
    % Try to read in the given non-dpx file.
    imageArr = uint16(imread(fileName, fileExt));
    % Find the bit depth per color channel. For instance, Matlab reports
    % three 8-bit channels as 24 bits per pixel.
    fileInfo = imfinfo(fileName);
    if (ismatrix(imageArr) == true)
        bitDepth = double(fileInfo.BitDepth);
    else
        bitDepth = double(fileInfo.BitDepth)/size(imageArr, 3);
    end
else
    warning('SoundRestoration:readImageFile:UnsupportedImageFormat', ...
        '(in readImageFile) Unsupported image format %s.\n', fileExt);
    imageArr = [];
    bitDepth = [];
end

return;
% end of the function "readImageFile"
